package com.tianhua.javs.core.func.script;

import com.tianhua.javs.client.bean.ScriptVarMappingBean;
import com.tianhua.javs.client.bean.TranslateResultBean;
import com.tianhua.javs.client.func.IScriptFunc;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Description:
 * date: 2022/2/11
 *
 * @author shenshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Component(value = "iteratorFunc")
public class IteratorFunc implements IScriptFunc {

    @Override
    public TranslateResultBean translate(String keyWardStr, Map<String, List<ScriptVarMappingBean>> javsVarMap) {

        String tempSegment = keyWardStr;
        String trimSegment = keyWardStr.trim();
        if(trimSegment.startsWith("fore(")){
            tempSegment = keyWardStr.replaceFirst("fore\\(","for(");
            replace(tempSegment, javsVarMap,"","");
        }
        if(trimSegment.contains("sfore(")){
            tempSegment = keyWardStr.replaceFirst("\\)","").replaceFirst("sfore\\(","stream().forEach(");
            replace(tempSegment, javsVarMap,"","");
            tempSegment = tempSegment + ";";
        }
        return TranslateResultBean.getInstance(tempSegment);
    }

    private String replace(String tempSegment, Map<String, List<ScriptVarMappingBean>> javsVarMap,String keySuffix,String valueSuffix){
        for (Map.Entry<String,List<ScriptVarMappingBean>> entry : javsVarMap.entrySet()){
            for (ScriptVarMappingBean scriptVarMappingBean : entry.getValue()){
                tempSegment = tempSegment.replace(scriptVarMappingBean.getJavsVarCode()+keySuffix,scriptVarMappingBean.getJavaCode()+valueSuffix);
            }
        }
        return tempSegment;
    }
}
